<template>
    <div class="attendance-manage">
        <el-tabs v-model="activeTab" @tab-click="onTabClick">
            <el-tab-pane label="今日考勤" name="today" />
            <el-tab-pane label="缺勤统计" name="absence" />
            <el-tab-pane label="历史考勤" name="history" />
            <el-tab-pane label="请假管理" name="leave" />
            <el-tab-pane label="离校管理" name="leaveSchool" />
            <el-tab-pane label="考勤时间设置" name="setting" />
        </el-tabs>
        <div class="filter-bar">
            <el-date-picker v-model="date" type="date" placeholder="选择日期" style="width: 150px; margin-right: 10px;" />
            <el-select v-model="timePeriod" placeholder="时间段" style="width: 120px; margin-right: 10px;">
                <el-option label="上午" value="上午" />
                <el-option label="下午" value="下午" />
            </el-select>
            <el-select v-model="className" placeholder="班级" style="width: 150px; margin-right: 10px;">
                <el-option v-for="item in classOptions" :key="item" :label="item" :value="item" />
            </el-select>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset" style="margin-left: 8px;">重置</el-button>
            <el-button type="success" @click="showManualRecordDialog" style="margin-left: 8px;">手动录入</el-button>
            <el-button type="warning" @click="handleExport" style="margin-left: 8px;">导出数据</el-button>
            <el-button type="info" @click="handleRefresh" style="margin-left: 8px;">
                <el-icon>
                    <Refresh />
                </el-icon> 刷新数据
            </el-button>
        </div>
        <div class="result-info">查询结果：共计 {{ tableData.length }} 条数据</div>
        <el-table :data="tableData" border style="width: 100%; margin-top: 10px;" v-loading="loading">
            <el-table-column prop="timePeriod" label="时间段" width="80" />
            <el-table-column prop="className" label="班级" width="120" />
            <el-table-column prop="total" label="总人数" width="80" />
            <el-table-column prop="present" label="实到人数" width="90" />
            <el-table-column prop="absent" label="缺勤人数" width="90" />
            <el-table-column prop="attendanceRate" label="出勤率" width="90" />
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-link type="primary" @click="viewDetail(scope.row)" style="margin-right: 10px;">考勤详情</el-link>
                    <el-link type="success" @click="editAttendance(scope.row)">编辑</el-link>
                </template>
            </el-table-column>
        </el-table>

        <!-- 考勤详情弹窗 -->
        <el-dialog v-model="detailDialogVisible" title="考勤详情" width="70%">
            <div class="detail-header">
                <el-descriptions :column="3" border>
                    <el-descriptions-item label="日期">{{ currentDetailDate }}</el-descriptions-item>
                    <el-descriptions-item label="时间段">{{ currentDetailTimePeriod }}</el-descriptions-item>
                    <el-descriptions-item label="班级">{{ currentDetailClassName }}</el-descriptions-item>
                    <el-descriptions-item label="总人数">{{ currentDetailTotal }}</el-descriptions-item>
                    <el-descriptions-item label="实到人数">{{ currentDetailPresent }}</el-descriptions-item>
                    <el-descriptions-item label="出勤率">{{ currentDetailRate }}</el-descriptions-item>
                </el-descriptions>
            </div>

            <div class="detail-content">
                <h4>学生考勤明细：</h4>
                <el-table :data="detailData" border v-loading="detailLoading" style="margin-top: 10px;">
                    <el-table-column prop="studentName" label="学生姓名" width="120" />
                    <el-table-column prop="studentId" label="学号" width="150" />
                    <el-table-column prop="status" label="考勤状态" width="120">
                        <template #default="scope">
                            <el-tag :type="getStatusType(scope.row.status)">
                                {{ scope.row.status }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="reason" label="缺勤原因" min-width="200" />
                </el-table>
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 手动录入弹窗 -->
        <el-dialog v-model="manualRecordDialogVisible" title="手动录入考勤" width="80%">
            <div class="manual-record-form">
                <el-form :model="manualRecordForm" label-width="100px">
                    <el-row :gutter="20">
                        <el-col :span="8">
                            <el-form-item label="日期">
                                <el-date-picker v-model="manualRecordForm.date" type="date" placeholder="选择日期"
                                    style="width: 100%;" value-format="YYYY-MM-DD" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="时间段">
                                <el-select v-model="manualRecordForm.timePeriod" placeholder="选择时间段"
                                    style="width: 100%;">
                                    <el-option label="上午" value="上午" />
                                    <el-option label="下午" value="下午" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="班级">
                                <el-select v-model="manualRecordForm.className" placeholder="选择班级" style="width: 100%;">
                                    <el-option v-for="item in classOptions" :key="item" :label="item" :value="item" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <div class="student-list-header">
                <h3>学生考勤列表</h3>
                <el-button type="primary" size="small" @click="addStudentRecord">添加学生</el-button>
            </div>

            <div class="manual-record-table">
                <el-table :data="manualRecordStudents" border style="width: 100%;">
                    <el-table-column prop="studentName" label="学生姓名" width="120">
                        <template #default="scope">
                            <el-input v-model="scope.row.studentName" placeholder="输入姓名" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="studentId" label="学号" width="150">
                        <template #default="scope">
                            <el-input v-model="scope.row.studentId" placeholder="输入学号" />
                        </template>
                    </el-table-column>
                    <el-table-column label="考勤状态" width="180">
                        <template #default="scope">
                            <el-select v-model="scope.row.status" placeholder="选择状态" style="width: 100%;">
                                <el-option label="正常" value="正常" />
                                <el-option label="缺勤" value="缺勤" />
                                <el-option label="迟到" value="迟到" />
                                <el-option label="早退" value="早退" />
                                <el-option label="请假" value="请假" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="缺勤原因">
                        <template #default="scope">
                            <el-input v-model="scope.row.reason" placeholder="填写缺勤原因"
                                :disabled="scope.row.status === '正常'" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="80" align="center">
                        <template #default="scope">
                            <el-button type="danger" size="small" circle @click="removeStudentRecord(scope.$index)">
                                <el-icon>
                                    <Delete />
                                </el-icon>
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="manualRecordDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitManualRecord" :loading="submitting">保存</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 编辑考勤弹窗 -->
        <el-dialog v-model="editDialogVisible" title="编辑考勤记录" width="80%">
            <el-table :data="editData" border>
                <el-table-column prop="studentName" label="学生姓名" width="100" />
                <el-table-column prop="studentId" label="学号" width="120" />
                <el-table-column label="考勤状态" width="180">
                    <template #default="scope">
                        <el-select v-model="scope.row.status" placeholder="选择状态">
                            <el-option label="正常" value="正常" />
                            <el-option label="缺勤" value="缺勤" />
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="缺勤原因">
                    <template #default="scope">
                        <el-input v-model="scope.row.reason" placeholder="填写缺勤原因"
                            :disabled="scope.row.status !== '缺勤'" />
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="saveEditAttendance" :loading="submitting">保存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Delete } from '@element-plus/icons-vue'

// 导入API及类型
import {
    getClassList,
    getTodayAttendance,
    getAttendanceDetail,
    manualRecordAttendance,
    exportAttendanceData,
    resetCache
} from '../../api/kaoqin'
import type {
    AttendanceItem,
    AttendanceDetailItem,
    ClassItem
} from '../../api/kaoqin.d.ts'

const router = useRouter()
const route = useRoute()
const activeTab = ref('today')
const loading = ref(false)
const detailLoading = ref(false)
const detailDialogVisible = ref(false)
const detailData = ref<AttendanceDetailItem[]>([])
const submitting = ref(false)

// 手动录入相关
const manualRecordDialogVisible = ref(false)
const manualRecordForm = ref({
    date: new Date(),
    timePeriod: '上午',
    className: ''
})
// 模拟的学生列表
const manualRecordStudents = ref([
    { studentName: '张三', studentId: '202501001', status: '正常', reason: '' },
    { studentName: '李四', studentId: '202501002', status: '正常', reason: '' },
    { studentName: '王五', studentId: '202501003', status: '正常', reason: '' },
    { studentName: '赵六', studentId: '202501004', status: '正常', reason: '' }
])

// 编辑考勤相关
const editDialogVisible = ref(false)
const editData = ref<AttendanceDetailItem[]>([])
const currentEditId = ref('')

// 考勤详情相关
const currentDetailId = ref('')
const currentDetailDate = ref('')
const currentDetailTimePeriod = ref('')
const currentDetailClassName = ref('')
const currentDetailTotal = ref('')
const currentDetailPresent = ref('')
const currentDetailRate = ref('')

// 监听路由变化高亮对应tab
watch(
    () => route.path,
    (path) => {
        if (path.includes('/main/attendance/manage')) {
            activeTab.value = 'today'
        } else if (path.includes('/main/attendance/absence')) {
            activeTab.value = 'absence'
        } else if (path.includes('/main/attendance/history')) {
            activeTab.value = 'history'
        } else if (path.includes('/main/attendance/leave')) {
            activeTab.value = 'leave'
        } else if (path.includes('/main/attendance/leaveSchool')) {
            activeTab.value = 'leaveSchool'
        } else if (path.includes('/main/attendance/setting')) {
            activeTab.value = 'setting'
        }
    },
    { immediate: true }
)

// tab点击时跳转到对应路由
function onTabClick(tab: any) {
    if (tab.paneName === 'today') {
        router.push('/main/attendance/manage')
    } else if (tab.paneName === 'absence') {
        router.push('/main/attendance/absence')
    } else if (tab.paneName === 'history') {
        router.push('/main/attendance/history')
    } else if (tab.paneName === 'leave') {
        router.push('/main/attendance/leave')
    } else if (tab.paneName === 'leaveSchool') {
        router.push('/main/attendance/leaveSchool')
    } else if (tab.paneName === 'setting') {
        router.push('/main/attendance/setting')
    }
}

const date = ref('2025-03-15')
const timePeriod = ref('')
const className = ref('')
const classOptions = ref<string[]>([])

// 静态数据，作为备用
const staticData: AttendanceItem[] = [
    { id: '1', timePeriod: '上午', className: '一年级（1）班', total: 51, present: 50, absent: 1, attendanceRate: '98%' },
    { id: '2', timePeriod: '下午', className: '一年级（1）班', total: 51, present: 48, absent: 2, attendanceRate: '96%' },
    { id: '3', timePeriod: '上午', className: '一年级（2）班', total: 42, present: 40, absent: 2, attendanceRate: '95.2%' },
    { id: '4', timePeriod: '下午', className: '一年级（2）班', total: 42, present: 41, absent: 1, attendanceRate: '97.6%' }
]

const tableData = ref<AttendanceItem[]>(staticData)

// 获取班级列表
async function fetchClassList() {
    try {
        const response = await getClassList()
        if (response.data && response.data.code === 200) {
            classOptions.value = response.data.data.map((item: ClassItem) => item.className)
        } else {
            // 回退到静态数据
            classOptions.value = ['一年级（1）班', '一年级（2）班']
            console.error('获取班级列表出错，使用静态数据')
        }
    } catch (error) {
        console.error('获取班级列表失败:', error)
        // 回退到静态数据
        classOptions.value = ['一年级（1）班', '一年级（2）班']
    }
}

// 查询考勤数据
async function fetchAttendanceData() {
    loading.value = true
    try {
        const params = {
            date: date.value,
            timePeriod: timePeriod.value,
            className: className.value
        }

        const response = await getTodayAttendance(params)

        if (response.data && response.data.code === 200) {
            tableData.value = response.data.data
        } else {
            // 回退到静态数据
            tableData.value = staticData
            console.error('获取考勤数据出错，使用静态数据')
        }
    } catch (error) {
        console.error('获取考勤数据失败:', error)
        // 回退到静态数据
        tableData.value = staticData
    } finally {
        loading.value = false
    }
}

// 查询按钮
function handleQuery() {
    fetchAttendanceData()
}

// 重置按钮
function handleReset() {
    date.value = '2025-03-15'
    timePeriod.value = ''
    className.value = ''
    fetchAttendanceData()
}

// 刷新数据按钮 - 重置缓存并获取新的动态数据
async function handleRefresh() {
    loading.value = true
    try {
        // 重置API缓存，生成新的随机数据
        resetCache()

        ElMessage({
            message: '正在刷新数据...',
            type: 'info'
        })

        // 重新获取班级和考勤数据
        await fetchClassList()
        await fetchAttendanceData()

        ElMessage({
            message: '数据刷新成功！',
            type: 'success'
        })
    } catch (error) {
        console.error('刷新数据失败:', error)
        ElMessage.error('刷新数据失败')
    } finally {
        loading.value = false
    }
}

// 添加获取考勤状态类型的函数
function getStatusType(status: string): string {
    switch (status) {
        case '正常':
            return 'success'
        case '缺勤':
            return 'danger'
        case '迟到':
            return 'warning'
        case '早退':
            return 'warning'
        case '请假':
            return 'info'
        default:
            return 'info'
    }
}

// 查看详情
async function viewDetail(row: any) {
    detailDialogVisible.value = true
    detailLoading.value = true

    try {
        const response = await getAttendanceDetail(row.id)

        if (response.data && response.data.code === 200) {
            detailData.value = response.data.data

            // 设置考勤详情头部信息
            currentDetailDate.value = row.date || formatDate(new Date())
            currentDetailTimePeriod.value = row.timePeriod || '上午'
            currentDetailClassName.value = row.className || ''
            currentDetailTotal.value = row.total ? row.total.toString() : '0'
            currentDetailPresent.value = row.present ? row.present.toString() : '0'
            currentDetailRate.value = row.attendanceRate || '0%'
        } else {
            // 后备方案
            ElMessage.error('获取详情失败')
            detailData.value = []
        }
    } catch (error) {
        console.error('获取考勤详情失败:', error)
        ElMessage.error('获取考勤详情失败')
        detailData.value = []
    } finally {
        detailLoading.value = false
    }
}

// 显示手动录入弹窗
function showManualRecordDialog() {
    manualRecordDialogVisible.value = true
    manualRecordForm.value = {
        date: new Date(),
        timePeriod: '上午',
        className: classOptions.value[0] || ''
    }
}

// 提交手动录入
async function submitManualRecord() {
    if (!manualRecordForm.value.className) {
        ElMessage.warning('请选择班级')
        return
    }

    // 验证学生数据是否正确
    if (manualRecordStudents.value.length === 0) {
        ElMessage.warning('请至少添加一名学生')
        return
    }

    // 验证所有学生数据是否完整
    for (const student of manualRecordStudents.value) {
        if (!student.studentName || !student.studentId) {
            ElMessage.warning('请填写完整的学生信息')
            return
        }
        if (student.status !== '正常' && !student.reason) {
            ElMessage.warning('请为缺勤/迟到/早退/请假学生填写原因')
            return
        }
    }

    submitting.value = true
    try {
        // 格式化日期
        const formattedDate = formatDate(manualRecordForm.value.date)

        // 获取考勤记录
        const records = manualRecordStudents.value.map(student => ({
            studentName: student.studentName,
            studentId: student.studentId,
            status: student.status,
            reason: student.reason
        }))

        const data = {
            date: formattedDate,
            timePeriod: manualRecordForm.value.timePeriod,
            className: manualRecordForm.value.className,
            records: records
        }

        const response = await manualRecordAttendance(data)

        if (response.data && response.data.code === 200) {
            ElMessage.success('考勤录入成功')

            // 将新添加的记录直接添加到表格数据中，实现即时显示
            if (response.data.data && 'attendanceRecord' in response.data.data) {
                // 类型断言以处理类型问题
                const responseData = response.data.data as {
                    attendanceRecord: AttendanceItem,
                    details: AttendanceDetailItem[]
                };

                // 添加到表格数据顶部
                tableData.value.unshift(responseData.attendanceRecord)

                // 保存详情数据，以便查看详情时可以显示
                detailData.value = responseData.details || []

                // 设置详情对话框的信息
                currentDetailId.value = responseData.attendanceRecord.id
                currentDetailDate.value = responseData.attendanceRecord.date || formattedDate
                currentDetailTimePeriod.value = responseData.attendanceRecord.timePeriod || manualRecordForm.value.timePeriod
                currentDetailClassName.value = responseData.attendanceRecord.className || manualRecordForm.value.className
                currentDetailTotal.value = responseData.attendanceRecord.total.toString()
                currentDetailPresent.value = responseData.attendanceRecord.present.toString()
                currentDetailRate.value = responseData.attendanceRecord.attendanceRate

                // 自动打开详情对话框显示新添加的数据
                detailDialogVisible.value = true

                // 清空表单数据，为下一次添加做准备
                resetManualRecordForm()
            } else {
                // 如果没有返回数据，则刷新列表
                fetchAttendanceData()
            }

            manualRecordDialogVisible.value = false
        } else {
            ElMessage.error('考勤录入失败')
        }
    } catch (error) {
        console.error('考勤录入失败:', error)
        ElMessage.error('考勤录入失败，请重试')
    } finally {
        submitting.value = false
    }
}

// 重置手动录入表单
function resetManualRecordForm() {
    manualRecordForm.value = {
        date: new Date(),
        timePeriod: '上午',
        className: classOptions.value[0] || ''
    }

    manualRecordStudents.value = [
        { studentName: '张三', studentId: '202501001', status: '正常', reason: '' },
        { studentName: '李四', studentId: '202501002', status: '正常', reason: '' },
        { studentName: '王五', studentId: '202501003', status: '正常', reason: '' },
        { studentName: '赵六', studentId: '202501004', status: '正常', reason: '' }
    ]
}

// 导出数据
async function handleExport() {
    ElMessageBox.confirm('确定要导出当前查询的考勤数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const params = {
                startDate: date.value,
                endDate: date.value,
                className: className.value
            }

            const response = await exportAttendanceData(params)

            if (response.data && response.data.code === 200) {
                ElMessage.success('导出成功')
                // 实际项目中，这里应该处理文件下载
                // const blob = new Blob([response.data])
                // const url = window.URL.createObjectURL(blob)
                // const link = document.createElement('a')
                // link.href = url
                // link.download = `考勤数据_${date.value}.xlsx`
                // link.click()
            } else {
                ElMessage.error('导出失败')
            }
        } catch (error) {
            console.error('导出数据失败:', error)
            ElMessage.error('导出数据失败，请重试')
        }
    }).catch(() => {
        // 取消导出
    })
}

// 编辑考勤
async function editAttendance(row: AttendanceItem) {
    editDialogVisible.value = true
    currentEditId.value = row.id

    try {
        const response = await getAttendanceDetail(row.id)

        if (response.data && response.data.code === 200) {
            editData.value = [...response.data.data] // 深拷贝数据
        } else {
            ElMessage.error('获取详情失败')
            editData.value = []
        }
    } catch (error) {
        console.error('获取考勤详情失败:', error)
        ElMessage.error('获取考勤详情失败')
        editData.value = []
    }
}

// 保存编辑后的考勤
async function saveEditAttendance() {
    submitting.value = true
    try {
        // 在实际项目中，这里应该调用API保存修改
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))

        ElMessage.success('考勤信息修改成功')
        editDialogVisible.value = false
        fetchAttendanceData() // 刷新数据
    } catch (error) {
        console.error('保存考勤信息失败:', error)
        ElMessage.error('保存考勤信息失败，请重试')
    } finally {
        submitting.value = false
    }
}

// 日期格式化工具函数
function formatDate(date: Date | string): string {
    if (typeof date === 'string') {
        return date
    }

    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')

    return `${year}-${month}-${day}`
}

// 添加学生记录
function addStudentRecord() {
    manualRecordStudents.value.push({
        studentName: '',
        studentId: '',
        status: '正常',
        reason: ''
    })
}

// 移除学生记录
function removeStudentRecord(index: number) {
    manualRecordStudents.value.splice(index, 1)
}

// 组件挂载时获取数据
onMounted(() => {
    fetchClassList()
    fetchAttendanceData()
})
</script>

<style scoped>
.attendance-manage {
    background: #f7fafd;
    padding: 20px;
}

.filter-bar {
    margin: 20px 0 10px 0;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}

.result-info {
    margin-bottom: 10px;
    color: #409eff;
}

.manual-record-form {
    margin-bottom: 20px;
}

.student-list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 20px 0 15px;
    padding: 0 5px;
}

.student-list-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: bold;
    color: #303133;
}

.manual-record-table {
    margin-top: 20px;
    max-height: 400px;
    overflow-y: auto;
}
</style>